package com.example.uploaddownload.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

@Controller
public class FileController {

    @GetMapping("/toUpload")
    public String toUpload(){
        return "upload";
    }


    @PostMapping("uploadFile")
    public String uploadFile(MultipartFile[] fileUpload, Model model) {
        //返回上传成功的状态信息
        model.addAttribute("uploadStatus","上传成功");
        //上传文件逻辑
        for (MultipartFile file : fileUpload){
            //获取上传文件的名称和后缀名
            String originalFilename = file.getOriginalFilename();
            //重新生成文件名
            String filename = UUID.randomUUID() + "-" + originalFilename;
            //设置存储目录
            String dirPath = "G:/file/";
            //如果文件不存在需创建
            File file1 = new File(dirPath);
            if (!file1.exists()){
                file1.mkdir();
            }
            try {
                file.transferTo(new File(dirPath+filename));
            } catch (IOException e) {
                e.printStackTrace();
                model.addAttribute("uploadStatus","上传失败");
            }
        }
        return "upload";
    }

    @GetMapping("/toDownload")
    public String toDownLoad(){
        return "download";
    }

    @GetMapping("/download")
    public ResponseEntity<byte[]> fileDownload(String filename,HttpServletRequest request) throws Exception {
        //指定要下载的文件路径
        String dirPath = "G:/file/";
        //创建文件对象
        File file = new File(dirPath + File.separator + filename);
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        filename=getFilename(request,filename);
        //通知浏览器以下载的形式打开
        headers.setContentDispositionFormData("attachment",filename);
        //定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        try{
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        } catch (IOException e){
            e.printStackTrace();
            return new ResponseEntity<>(e.getMessage().getBytes(),HttpStatus.EXPECTATION_FAILED);
        }
    }

    // 根据浏览器的不同进行编码设置，返回编码后的文件名
    private String getFilename(HttpServletRequest request, String filename)
            throws Exception {
        // IE不同版本User-Agent中出现的关键词
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        // 获取请求头代理信息
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                //IE内核浏览器，统一为UTF-8编码显示，并对转换的+进行更正
                return URLEncoder.encode(filename, "UTF-8").replace("+"," ");
            }
        }
        //火狐等其它浏览器统一为ISO-8859-1编码显示
        return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
    }
}
